package com.hundsun.cprs.yyt.service.common.service.impl;

import java.text.MessageFormat;
import java.util.*;

import com.hundsun.cprs.yyt.service.common.dto.*;
import com.hundsun.cprs.yyt.service.common.query.UserQuery;
import com.hundsun.cprs.yyt.service.common.service.RemoteBrokerService;
import com.hundsun.cprs.yyt.service.rabbit.RoutingKeyConstants;
import com.hundsun.cprs.yyt.service.system.enums.EnumBussinessParam;
import com.hundsun.cprs.yyt.service.system.service.BusinessParamHelper;
import com.hundsun.cprs.yyt.util.BeanUtils;
import com.hundsun.cprs.yyt.common.base.BaseService;
import com.hundsun.cprs.yyt.common.enums.EnumBusinessCode;
import com.hundsun.cprs.yyt.common.enums.EnumCommonCode;
import com.hundsun.cprs.yyt.common.exception.ServiceCodeException;
import com.hundsun.cprs.yyt.common.exception.ServiceException;
import com.hundsun.cprs.yyt.service.common.dto.*;
import com.hundsun.cprs.yyt.service.common.enums.EnumUserPwdType;
import com.hundsun.cprs.yyt.service.common.enums.EnumUserType;
import com.hundsun.cprs.yyt.service.common.query.UserQuery;
import com.hundsun.cprs.yyt.service.common.service.RemoteUserService;
import com.hundsun.cprs.yyt.util.Base64Util;
import com.hundsun.cprs.yyt.util.BeanUtils;
import com.hundsun.network.uc.biz.util.CommonUtils;
import com.hundsun.network.uc.client.dto.SessionTokenInfo;
import com.hundsun.network.uc.common.consts.UserConstants;
import com.hundsun.network.uc.external.dto.req.*;
import com.hundsun.network.ue.common.external.dto.req.EmpiricalChangeReq;
import com.hundsun.network.ue.common.external.dto.resp.EmpiricalChangeResult;
import com.hundsun.network.ue.enums.EnumEmpiricalLeveChangeType;
import com.yunyong.encrypt.EncryptUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.hundsun.cprs.yyt.common.base.BaseService;
import com.hundsun.cprs.yyt.common.enums.EnumBusinessCode;
import com.hundsun.cprs.yyt.common.enums.EnumCommonCode;
import com.hundsun.cprs.yyt.common.exception.ServiceCodeException;
import com.hundsun.cprs.yyt.common.exception.ServiceException;
import com.hundsun.cprs.yyt.service.common.enums.EnumUserPwdType;
import com.hundsun.cprs.yyt.service.common.enums.EnumUserType;
import com.hundsun.cprs.yyt.service.common.service.RemoteUserService;
import com.hundsun.cprs.yyt.service.system.SystemConfigProperties;
import com.hundsun.cprs.yyt.service.system.service.BussinessParamService;
import com.hundsun.cprs.yyt.util.Base64Util;
import com.hundsun.jresplus.common.util.StringUtil;
import com.hundsun.jresplus.remoting.exception.RemotingServiceException;
import com.hundsun.network.uc.biz.enums.EnumFileType;
import com.hundsun.network.uc.biz.enums.EnumPwdType;
import com.hundsun.network.uc.biz.enums.EnumRelateType;
import com.hundsun.network.uc.biz.enums.EnumYesOrNo;
import com.hundsun.network.uc.biz.enums.UserSourceEnum;
import com.hundsun.network.uc.client.req.UserRequest;
import com.hundsun.network.uc.client.result.UcResult;
import com.hundsun.network.uc.client.service.RemoteUcService;
import com.hundsun.network.uc.exception.BusinessBaseException;
import com.hundsun.network.uc.external.api.IActiveService;
import com.hundsun.network.uc.external.api.IMemberService;
import com.hundsun.network.uc.external.api.IUserLuceneService;
import com.hundsun.network.uc.external.dto.resp.UserSaveResult;
import com.hundsun.network.ue.biz.ybk.service.RemoteBidService;
import com.hundsun.network.ue.biz.ybk.service.RemoteMchtService;
import com.hundsun.network.ue.client.remote.dto.UploadFileResult;
import com.hundsun.network.ue.crtp.external.api.IUcThirdAuthService;
import com.hundsun.network.ue.crtp.external.dto.req.UserBindRequest;
import com.hundsun.network.ue.crtp.external.dto.resp.UserBindResponse;
import com.hundsun.network.ue.ybk.external.api.ISecurityService;
import org.springframework.util.CollectionUtils;

@Service("remoteUserService")
public class RemoteUserServiceImpl extends BaseService implements RemoteUserService {

	protected final Log logger = LogFactory.getLog(this.getClass());
	protected final String defaultRefereeIsRequired = "T";	
	protected final String bussinessKey = "bid_referee_isRequired";
	
	@Value("${hbs.exchangeId:0}")
	private String exchangeId;

	@Value("${login.info.encryptkey}")
	private String encryptKey;

	@Autowired(required=false)
	private RemoteUcService remoteUcService;

	@Autowired(required=false)
	private IActiveService iActiveService;
	
	@Autowired(required=false)
	private RemoteMchtService remoteMchtService;
	
	@Autowired(required=false)
	private IMemberService iMemberService;
	
	@Autowired(required=false)
	private IUserLuceneService iUserLuceneService;
	
	@Autowired(required=false)
	private ISecurityService iSercurityService;
	
	@Autowired(required=false)
	private com.hundsun.network.uc.external.api.ISecurityService iSecurityService2;
	
	@Autowired
	private RabbitTemplate rabbitTemplate;
	
	@Autowired(required=false)
	private RemoteBidService remoteBidService;
	@Autowired(required=false)
	private IUcThirdAuthService iUcThirdAuthService;
	
	@Autowired
	private BussinessParamService bussinessParamService;

	@Autowired
	private RemoteBrokerService remoteBrokerService;

	/**
	 * 用户登录实现
	 * 
	 * @param request
	 * @return
	 * @see com.hundsun.network.gates.luosi.wulin.reomte.service.RemoteUserService#login(com.hundsun.UserLoginInfo.gates.luosi.wulin.reomte.request.UserLoginRequest)
	 */

	/**
	 * 根据用户名，获取用户信息
	 */
	public UserLoginResult getUserMsgByAccount(UserLoginInfo request) {
		UserLoginResult result = new UserLoginResult();
		try {
			UserRequest req = new UserRequest();
			req.setAccount(request.getUserAccount());
			req.setUserId(request.getUserId());
			req.setParentId(-1L);
			req.setIsDetail("1");
			List<Map<String, String>> list = remoteUcService.getUsersList(req);
			if (list != null && list.size() > 0) {
				Map<String, String> map = remoteUcService.getUsersList(req).get(0);
				result.setUserAccountDTO(convertFrom(map));
			} else {
				logger.error("交易商" + request.getUserAccount() + "信息异常");
			}
		} catch (Exception e) {
			logger.error("", e);
		}
		return result;
	}

	@Override
	public UserLoginResult getUserListByAccount(UserLoginInfo request) {
		UserLoginResult result = new UserLoginResult();
		try {
			UserRequest req = new UserRequest();
			Map<String, Object> queryMap=new HashMap<String, Object>();
			if(request.getUserAccount()!=null){
				//req.setAccount(request.getUserAccount());
				queryMap.put("partFullName", request.getUserAccount());
			}
			if(request.getCellPhone()!=null){				
				queryMap.put("cellPhoneRef", request.getCellPhone());				
			}
			if(request.getFundAccount()!=null){
				queryMap.put("partCode", request.getFundAccount());
			}
			//status=3是控制交易商被禁用之后，不允许被查询
			queryMap.put("status","3");
			/*if(request.getPartCategories1()!=null){
				queryMap.put("partCategories1", request.getPartCategories1());
			}*/
			req.setQueryMap(queryMap);
			req.setParentId(-1L);
			req.setPageSize(998);
			req.setFormCode("MCHT_USER_FORM");
			List<Map<String, String>> list = remoteUcService.getUsersListfromDb(req);
			List<UserAccountDTO> userAccountDTOs = new ArrayList<UserAccountDTO>();
			if (list != null && list.size() > 0) {
				for(Map<String, String> map:list){
					userAccountDTOs.add(convertFrom(map));
				}				
				result.setUserAccountDTOs(userAccountDTOs);
			} else {
				logger.error("交易商" + request.getUserAccount() + "信息异常");
			}
		} catch (Exception e) {
			logger.error("查询会员列表", new ServiceException(e));
		}
		return result;
	}

	@Override
	public UserQuery getUserListByAccount(UserQuery query) {
		UserQuery userQuery = new UserQuery();
		try {
			UserRequest req = new UserRequest();
			Map<String, Object> queryMap=new HashMap<String, Object>();
			if(query.getUserAccount()!=null){
				queryMap.put("partFullName", query.getUserAccount());
			}
			if(query.getCellPhone()!=null){
				queryMap.put("cellPhoneRef", query.getCellPhone());
			}
			if(query.getFundAccount()!=null){
				queryMap.put("partCode", query.getFundAccount());
			}
			queryMap.put("status","3");
			req.setQueryMap(queryMap);
			req.setParentId(-1L);
			req.setCurrPage(query.getPageNo());
			req.setPageSize(query.getPageSize());
			req.setFormCode("MCHT_USER_FORM");
			List<Map<String, String>> list = remoteUcService.getUsersListfromDb(req);
			List<UserAccountDTO> userAccountDTOs = new ArrayList<UserAccountDTO>();
			if (list != null && list.size() > 0) {
				for(Map<String, String> map:list){
					userAccountDTOs.add(convertFrom(map));
				}
				userQuery.setData(userAccountDTOs);
				userQuery.setTotalCount(Integer.parseInt(list.get(0).get("totalItem")));
			} else {
				logger.error("交易商" + userQuery.getUserAccount() + "信息异常");
			}
		} catch (Exception e) {
			logger.error("查询会员列表", new ServiceException(e));
		}
		return userQuery;
	}

	@Override
	public UserAccountDTO login(String account, String password, String loginIp, String bizType) throws ServiceCodeException {
		UserAccountDTO userInfo = null;
		try {
			UcResult result = remoteUcService.sucLoginByAccount(account, password, loginIp, bizType, Integer.valueOf(exchangeId));
			//result.getErrorNo() === 0 这种方式判断有问题,返回码混乱
			if(Integer.parseInt(result.getIsSuccess()) == 1){
				//登录成功
				userInfo = convertFrom(result.getResult());
				userInfo.setSessionToken(result.getUserToken());
			}else{
				//针对不成功的请求，还是返回错误为0，做下转换
				int errorCode = result.getErrorCode() == 0?-1:result.getErrorCode();
				throw new ServiceCodeException(errorCode,result.getErrorMsg());
			}
		} catch (ServiceCodeException e) {
			throw e;
		} catch (Exception e) {
			logger.error("统一会员登录接口调用异常",new ServiceException(e));
			throw new ServiceCodeException(EnumCommonCode.COMMON_SERVER_ERROR.getErrorNo(),e.getMessage());
		}
		return userInfo;
	}

	@Override
	public UserAccountDTO encryptLogin(String encryptAccount, String encryptPassword, String loginIp, String bizType) {
		try {
			//account和password解密
			encryptAccount = EncryptUtil.restoreSymbol(encryptAccount);
			encryptPassword = EncryptUtil.restoreSymbol(encryptPassword);
			String account = EncryptUtil.decryptByAESAndBase64(encryptKey, encryptAccount);
			String password = EncryptUtil.decryptByAESAndBase64(encryptKey, encryptPassword);
			if (account == null || password == null) {
				throw new ServiceCodeException(EnumBusinessCode.BUSINESS_3201.getErrorNo(), EnumBusinessCode.BUSINESS_3201.getErrorInfo());
			}
			return this.login(account, password, loginIp, bizType);
		} catch (ServiceCodeException e) {
			throw e;
		} catch (Exception e) {
			logger.error("统一会员登录接口调用异常",new ServiceException(e));
			throw new ServiceCodeException(EnumCommonCode.COMMON_SERVER_ERROR.getErrorNo(),e.getMessage());
		}
	}

	/**
	 * 获取加密后的用户登录信息（账号+密码）
	 *
	 * @param userId
	 * @return
	 */
	@Override
	public UserLoginInfoEncryptDto encryptLoginInfo(Long userId) {
		try {
			Map<String, String> result = remoteBidService.getUserDetail(userId, null);
			if (result == null) {
				return null;
			}
			UserLoginInfoEncryptDto loginInfoEncryptDto = new UserLoginInfoEncryptDto();
			String account = result.get(UserConstants.U_REG_MOBILE);
			String password = result.get(UserConstants.U_PASSWORD);
			if (StringUtil.isBlank(account) || StringUtil.isBlank(password)) {
				throw new ServiceCodeException(EnumBusinessCode.BUSINESS_3202.getErrorNo(), EnumBusinessCode.BUSINESS_3202.getErrorInfo());
			}
			String encryptAccount = EncryptUtil.encryptByAESAndBase64(encryptKey, account);
			String encryptPassword = EncryptUtil.encryptByAESAndBase64(encryptKey, password);
			if (StringUtil.isBlank(encryptAccount) || StringUtil.isBlank(encryptPassword)) {
				throw new ServiceCodeException(EnumBusinessCode.BUSINESS_3203.getErrorNo(), EnumBusinessCode.BUSINESS_3203.getErrorInfo());
			}
            //去除换行符\r\n
            encryptAccount = encryptAccount.replaceAll("\\r\\n", "");
            encryptPassword = encryptPassword.replaceAll("\\r\\n", "");
            encryptAccount = EncryptUtil.escapeSymbol(encryptAccount);
            encryptPassword = EncryptUtil.escapeSymbol(encryptPassword);
			loginInfoEncryptDto.setUserId(Long.valueOf(result.get(UserConstants.U_ID)));
			loginInfoEncryptDto.setEncryptUserAccount(encryptAccount);
			loginInfoEncryptDto.setEncryptPassword(encryptPassword);
			return loginInfoEncryptDto;
		} catch (ServiceCodeException e) {
			throw e;
		} catch (BusinessBaseException e) {
			logger.error(e);
			return null;
		} catch (RemotingServiceException e) {
			logger.error(e);
			return null;
		}
	}

	@Override
	public UserAccountDTO tokenLogin(String sessionToken, String loginIp) {
		UserAccountDTO userInfo = null;
		try {
			String sessionId;
			SessionTokenInfo tokenInfo = CommonUtils.parseUserToke(sessionToken);
			if (tokenInfo == null || StringUtil.isEmpty(sessionId = tokenInfo.getSessionId())) {
				logger.warn(MessageFormat.format("sessionToken[{0}]不合法", sessionToken));
				throw new ServiceCodeException(EnumBusinessCode.BUSINESS_3205);
			}
			UserBaseReq userBaseReq = new UserBaseReq();
			userBaseReq.setSessionId(sessionId);
			userBaseReq.setClientToken(sessionToken);
			boolean online = iMemberService.isSessionValiad(userBaseReq);
			if (!online) {
				throw new ServiceCodeException(EnumBusinessCode.BUSINESS_3206);
			}
			Map<String, String> userMap = remoteUcService.getUserDetailByToken(userBaseReq);
			if (CollectionUtils.isEmpty(userMap)) {
				throw new ServiceCodeException(EnumBusinessCode.BUSINESS_3206);
			}
			userInfo = convertFrom(userMap);
			userInfo.setSessionToken(sessionToken);
		} catch (ServiceCodeException e) {
			throw e;
		} catch (Exception e) {
			logger.error("统一会员登录接口调用异常",new ServiceException(e));
			throw new ServiceCodeException(EnumCommonCode.COMMON_SERVER_ERROR.getErrorNo(),e.getMessage());
		}
		return userInfo;
	}

	@Override
	public void register(UserRegisterInfo registerInfo) throws ServiceCodeException {
		
		Map<String,String> userMap = new HashMap<String,String>();
		//经纪商账号若存在，则校验同时获取该信息
		if(StringUtils.isNotEmpty(registerInfo.getBrokerAccount())){
			UcResult result = remoteMchtService.getParentRelateMerge(registerInfo.getBrokerAccount(), Integer.valueOf(exchangeId));
			if(Integer.parseInt(result.getIsSuccess()) == 1){
				//填充经纪信息
				userMap.putAll(result.getResult());
			}else{
				//经纪商不存在
				throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1014.getErrorNo(),EnumBusinessCode.BUSINESS_1014.getErrorInfo());
			}
		}
		
		//从字典表中获取推荐人是否必填的配置信息
		String bussinessValue = bussinessParamService.getBussinessParamByKey(bussinessKey).getBussinessValue();
		//如果字典表中没有取到该配置信息，则系统默认推荐人信息为非必填
		if(bussinessValue.isEmpty()){
			bussinessValue="F";
		}

		//校验推荐人账号是否必填
		if(bussinessValue.equalsIgnoreCase(defaultRefereeIsRequired)){
			//推荐人账号不能为空
			if(StringUtils.isEmpty(registerInfo.getRefereeAccount())){
				throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1022.getErrorNo(),EnumBusinessCode.BUSINESS_1022.getErrorInfo());
			}
		}


		//推荐人推荐人数限制
		if(StringUtils.isNotEmpty(registerInfo.getRefereeAccount())){
			//从字典表中获取推荐人最大可推荐人数
			int limitReferNum = BusinessParamHelper.getIntValue(bussinessParamService, EnumBussinessParam.LIMIT_MORE_REFER_NUM, null);

			//获取推荐人信息
			UserAccountDTO userAccountDTO = this.getReferUsreId(registerInfo.getRefereeAccount());

			//推荐人推荐的人数不能超过信息
			int referNum = this.limitMoreReferNum(userAccountDTO.getId().toString());
			if(referNum >= limitReferNum){
				throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1029.getErrorNo(),EnumBusinessCode.BUSINESS_1029.getErrorInfo());
			}
		}


		userMap.put("userTypeSecond", EnumUserType.indexByValue(registerInfo.getUserType()).getMapCode());
//		userMap.put("account", registerInfo.getUcAccount());
		//推荐人交易账号
		userMap.put("refereeAccount", registerInfo.getRefereeAccount());		
		//填充会员信息
		userMap.put("cellPhone", registerInfo.getAccount());
		userMap.put("password", registerInfo.getPassword());
		userMap.put("code", registerInfo.getValidCode());
		//填充统一会员默认值 status:6;partCategories:toActiveRole
		userMap.put("status", "6");
		userMap.put("partCategories", "toActiveRole");
		
		//手机号码方式注册会员
		try {
			UserFormReq req = new UserFormReq();
			req.setBizType("mobileReg");
			req.setFormCode("MCHT_USER_FORM");
			req.setExchangeId(Integer.valueOf(exchangeId));
			req.setRegSource(UserSourceEnum.HESSIAN.getCode().toString());
			req.setUserMap(userMap);
			
			if(logger.isInfoEnabled()){
				logger.info(ToStringBuilder.reflectionToString(req));
			}
			UserSaveResult response = iMemberService.saveInfo(req);
			if(!response.isResult()){
				throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1008.getErrorNo(),EnumBusinessCode.BUSINESS_1008.getErrorInfo());
			}
			//拦截会员注册信息到rabbitmq
			rabbitTemplate.convertAndSend(RoutingKeyConstants.BID_USER_REGSITER, registerInfo);
			
			/*try {
				medalRabbitmqDataService.proxyHandle(registerInfo);
			} catch (ServiceCodeException e) {
				if(logger.isInfoEnabled()){
					logger.info("发送会员注册信息出错，请注意。",e);
				}
			} catch (Exception e) {
				if(logger.isInfoEnabled()){
					logger.info("发送会员注册信消息出错，请注意。",e);
				}
			}*/
	    } catch (ServiceCodeException e) {
	        throw e;
		} catch (BusinessBaseException e) {
			throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1008.getErrorNo(), e.getMessage());
		} catch (Exception e) {
		    throw new ServiceException(e);
		}
	}

	/**
	 * 获取推荐人userId
	 */
	private UserAccountDTO getReferUsreId(String fundAccount){
		UserAccountDTO userAccountDTO = this.getUserDetailByUserAccount(fundAccount);
		if(userAccountDTO == null){
			throw new ServiceCodeException("会员推荐人信息不存在");
		}

		return userAccountDTO;
	}

	/**
	 * 推荐人推荐的人数是否超过限制
	 */
	private int limitMoreReferNum(String userId){

		ReferRelateRequestDto request = new ReferRelateRequestDto();
		request.setUpUserId(userId);
		//获取会员推荐的人数
		BrokerReferRelateInfo brokerReferRelateInfo = remoteBrokerService.queryBrokerRelateList(request);
		if(brokerReferRelateInfo == null){
			return 0;
		}

		return brokerReferRelateInfo.getReferNum();
	}




	@Override
	public UserAccountDTO getUserDetailByUserId(Long userId) {
		try {
			Map<String, String> result = remoteBidService.getUserDetail(userId, null);
			return convertFrom(result);
		} catch (BusinessBaseException e) {
			logger.error("[userId:" + userId +"]",e);
			return null;
		} catch (RemotingServiceException e) {
			logger.error("[userId:" + userId +"]",e);
			return null;
		}
	}
	
	@Cacheable(value="UserInfoCache:Id",key="new String(#userId)")
	public UserAccountDTO getUserDetailFromCacheByUserId(Long userId){
	    return getUserDetailByUserId(userId);
	}
	
	@Override
	public UserAccountDTO getUpFirstParentByUserId(Long userId) {
		UserRequest userRequest = new UserRequest();
		userRequest.setUserId(userId);
		userRequest.setRelateType(EnumRelateType.AGENT_RELATE.getCode());
		userRequest.setFormCode("MID_USER_FORM");
		Map<String, String> result = remoteUcService.getUpRelateUser(userRequest);
		if(result == null || result.isEmpty()) {
			userRequest.setRelateType(EnumRelateType.COMMON.getCode());
			userRequest.setFormCode("AGENT_USER_FORM");
			result = remoteUcService.getUpRelateUser(userRequest);
		}
		if(result == null || result.isEmpty()) {
			return null;
		}
		return convertFrom(result);
	}

	@Override
	public UserAccountDTO getUserDetailByUserAccount(String account) {
		try {
			Map<String, String> result = remoteUcService.getUserDetail(null, account, Integer.parseInt(exchangeId));
			return convertFrom(result);
		} catch (BusinessBaseException e) {
			logger.warn("查询会员异常",e);
			return null;
		} catch (Exception e){
		    logger.warn("查询会员异常",e);
		    return null;
		}
	}

	@Override
	public UserAccountDTO getUserDetailByPhone(String phone) {
		UserBaseReq req = new UserBaseReq();
		req.setCellPhone(phone);
		Map<String, String> userInfoMap = iUserLuceneService.searchFirstByCellPhone(req);
		if(userInfoMap == null) 
			return null;
		return convertFrom(userInfoMap);
	}
	

    @Override
    public UserAccountDTO getUserDetailByFr(String fr) {
        try {
            //remoteBidService.uploadFileByte(null, EnumFileType.IMAGE.getCode());
            Map<String, String> result = remoteBidService.getUserDetailByPRCode(fr);
            return convertFrom(result);
        } catch (BusinessBaseException e) {
            logger.error(e);
            return null;
        } catch (RemotingServiceException e) {
            logger.error(e);
            return null;
        } catch (Exception e){
			logger.error(e);
			return null;
		}
    }
	
	@Override
	@CacheEvict(value="UserInfoCache:Id",key="new String(#userInfo.id)")
	public void modifyUser(UserAccountDTO userInfo) {
		
		Map<String,String> userMap = new HashMap<String,String>();
		userMap.put("partShortName", userInfo.getNickName());
		userMap.put("userId", userInfo.getId().toString());
		if(StringUtils.isNotEmpty(userInfo.getHeadImgUrl()))
		    userMap.put("profilePicture", userInfo.getHeadImgUrl());
		userMap.put("gender", userInfo.getGender());
		if(userInfo.getAge() != null)
			userMap.put("age", userInfo.getAge().toString());
		userMap.put("perEmail", userInfo.getEmail());
		userMap.put("commonRemark", userInfo.getRemak());
		if(StringUtils.isNotBlank(userInfo.getUserType())){
			userMap.put("userTypeSecond", EnumUserType.indexByValue(userInfo.getUserType()).getMapCode());
		}
		if (StringUtil.isNotBlank(userInfo.getCertificateType())) {
			userMap.put("certType", userInfo.getCertificateType());
		}
		userMap.put("partFullName", userInfo.getName());
		userMap.put("bank", userInfo.getBank());
		userMap.put("bankAccount", userInfo.getBankCard());
		userMap.put("payPwd", userInfo.getFundPassword());
		userMap.put("certNo", userInfo.getCertificateNum());
		if (StringUtil.isNotBlank(userInfo.getStatus()))
			userMap.put("status", userInfo.getStatus());
		if (StringUtil.isNotBlank(userInfo.getCertFrontImgUrl()))
		    userMap.put("imgAttach1", userInfo.getCertFrontImgUrl());
		if (StringUtil.isNotBlank(userInfo.getCertReverseImgUrl()))
		    userMap.put("imgAttach9", userInfo.getCertReverseImgUrl());
		try {
			UserFormReq req = new UserFormReq();
			req.setBizType("editInfo");
			req.setFormCode("MCHT_USER_FORM");
			req.setExchangeId(Integer.valueOf(exchangeId));
			req.setRegSource(UserSourceEnum.HESSIAN.getCode().toString());
			//编辑标识位：1-编辑，0-新增(默认)
			req.setIsEditStr("1");
			req.setUserMap(userMap);
			if(logger.isInfoEnabled()){
			    logger.info(ToStringBuilder.reflectionToString(req));
			}
			UserSaveResult response = iMemberService.saveInfo(req);
			if(!response.isResult()){
				throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1009.getErrorNo(),EnumBusinessCode.BUSINESS_1009.getErrorInfo());
			}
        } catch (ServiceCodeException e) {
            throw e;
        } catch (BusinessBaseException e) {
            //会员返回的业务报错异常类，竞购这么做下包装，以免错误码冲突
            throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1009.getErrorNo(), e.getMessage());
        } catch (Exception e) {
            throw new ServiceException(e);
        }
	}

	@Override
	public void updateMchtLevel(Long userId, Long mchtLevel) throws ServiceCodeException {
		//更新用户的交易商等级信息
		try {
			this.remoteBidService.updateMchtLevel(userId,mchtLevel);
		} catch (BusinessBaseException e) {
			if (logger.isErrorEnabled()) {
				logger.error("调用会员接口处理'更新用户的交易商等级信息'出错。", e);
			}
			throw new ServiceCodeException(EnumCommonCode.COMMON_SERVER_ERROR.getErrorNo(), e.getMessage());
		} catch (Exception e) {
           throw new ServiceException(e);
        }
	}

	@Override
	public void realNameVerify(UserAccountDTO userInfo) {
		Map<String,String> userMap = new HashMap<String,String>();
		
		//获取该会员的上级授权经纪信息
		/*UserRequest userRequest = new UserRequest();
		userRequest.setUserId(userInfo.getId());
		userRequest.setRelateType("1");
		userRequest.setExchangeId(Integer.valueOf(exchangeId));
		Map<String,String> upRelateUserMap =  remoteUcService.getUpRelateUser(userRequest);
		if(upRelateUserMap != null){
			userMap.put("parentRelateId", upRelateUserMap.get("userId"));
		}*/
		EnumUserType enumUserType = EnumUserType.indexByValue(userInfo.getUserType());
		userMap.put("userId", userInfo.getId().toString());
		if(StringUtils.isNotBlank(userInfo.getUserType())){
			userMap.put("userTypeSecond", enumUserType.getMapCode());
		}
		userMap.put("partFullName", userInfo.getName());
		userMap.put("bank", userInfo.getBank());
		userMap.put("bankAccount", userInfo.getBankCard());
		userMap.put("payPwd", userInfo.getFundPassword());
		userMap.put("certType", userInfo.getCertificateType());
		userMap.put("certNo", userInfo.getCertificateNum());
        if (StringUtil.isNotBlank(userInfo.getCertFrontImgUrl()))
            userMap.put("imgAttach1", userInfo.getCertFrontImgUrl());
        if (StringUtil.isNotBlank(userInfo.getCertReverseImgUrl()))
            userMap.put("imgAttach9", userInfo.getCertReverseImgUrl());
		try {
			UserFormReq req = new UserFormReq();
			req.setBizType("mobileReg");
			req.setFormCode("MCHT_USER_FORM");
			req.setExchangeId(Integer.valueOf(exchangeId));
			req.setRegSource(UserSourceEnum.HESSIAN.getCode().toString());
			//编辑标识位：1-编辑，0-新增(默认)
			req.setIsEditStr("1");
			req.setUserMap(userMap);
			if(logger.isInfoEnabled()){
				logger.info(ToStringBuilder.reflectionToString(req));
			}
			UserSaveResult response = iMemberService.saveInfo(req);
			
			if(logger.isInfoEnabled()){
				logger.info(ToStringBuilder.reflectionToString(response));
			}
			if(!response.isResult()){
				throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1010.getErrorNo(),EnumBusinessCode.BUSINESS_1010.getErrorInfo());
			}
			//拦截会员实名信息到rabbitmq
			rabbitTemplate.convertAndSend(RoutingKeyConstants.BID_USER_REALNAME, userMap);
        } catch (ServiceCodeException e) {
            throw e;
        } catch (BusinessBaseException e) {
			throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1009.getErrorNo(), e.getMessage());
        } catch (Exception e) {
            throw new ServiceException(e);
        }
	}

	@Override
	public void modifyLoginPwd(Long userId, String oldPwd, String newPwd,String pwdType) {
		// TODO Auto-generated method stub
		try {
			if(EnumPwdType.PAY_PWD.getCode().equals(pwdType)){
				//若是支付密码，则需要判断支付密码是否设定
				UserSecurityReq req = new UserSecurityReq();
				req.setUserId(userId.toString());
				req.setExchangeId(Integer.parseInt(exchangeId));
				boolean isSet = iSecurityService2.existPayPwd(req);
				if(!isSet){
					throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1015.getErrorNo(),"支付密码未设置，无需修改");
				}
			}
			boolean success = remoteUcService.changePwd(userId, null, oldPwd, newPwd, pwdType, Integer.parseInt(exchangeId));
			if(!success){
				throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1000.getErrorNo(),"修改密码失败");
			}
        } catch (ServiceCodeException e) {
            throw e;
        } catch (BusinessBaseException e) {
            throw new ServiceCodeException(Integer.valueOf(e.getErrorCode()),e.getMessage());
        } catch (RemotingServiceException e) {
			throw new ServiceCodeException(Integer.valueOf(e.getErrorCode()), e.getErrorMessage());
		} catch (Exception e) {
            throw new ServiceException(e);
        }
	}
	
	@Override
	public void modifyBindMobile(Long userId, String newPhone) {
		UserSecurityReq req = new UserSecurityReq();
		req.setNewMobile(newPhone);
		req.setUserId(userId.toString());
		try {
			boolean success = iSercurityService.changeMobile(req);
			if(success){
				//成功
			}else{
				throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1009.getErrorNo(),"修改会员手机号码失败");
			}
        } catch (ServiceCodeException e) {
            throw e;
        } catch (BusinessBaseException e) {
            throw new ServiceCodeException(Integer.valueOf(e.getErrorCode()),e.getMessage());
        } catch (Exception e) {
            throw new ServiceException(e);
        }
	}
	
	@Override
	public void resetPwdByForget(Long userId, String newPwd, String code,String pwdType) {
		try {
			UserBaseReq req = new UserBaseReq();
			req.setUserId(userId.toString());
			req.setPwdType(pwdType);//登录密码或者支付密码
			req.setActiveCode(code);
			req.setPassword(newPwd);
			boolean success = iSecurityService2.changePwdForForget(req);
			if(success){
				//成功
			}else{
				throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1000.getErrorNo(),"重置密码失败");
			}
        } catch (ServiceCodeException e) {
            throw e;
        } catch (BusinessBaseException e) {
            throw new ServiceCodeException(Integer.valueOf(e.getErrorCode()),e.getMessage());
        } catch (Exception e) {
            throw new ServiceException(e);
        }
	}
	

	@Override
	public void sendRegCheckCode(String phone) throws ServiceCodeException {
		try {
			CheckCodeReq req = new CheckCodeReq();
			req.setCellPhone(phone);
			boolean success = iActiveService.sendRegCheckCode(req);
			if(!success){
				throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1007.getErrorNo(),EnumBusinessCode.BUSINESS_1007.getErrorInfo());
			}
        } catch (ServiceCodeException e) {
            throw e;
        } catch (BusinessBaseException e) {
            throw new ServiceCodeException(Integer.valueOf(e.getErrorCode()),e.getMessage());
        } catch (Exception e) {
            throw new ServiceException(e);
        }
	}
	
	@Override
	public void sendCheckCode(Long userId, String bizType) throws ServiceCodeException {
		try {
			UserActiveReq req = new UserActiveReq();
			req.setUserId(userId);
			req.setSendType("sms");
			req.setType(bizType);
			String success = iActiveService.sendUserChkCode(req);
			if(!"1".equals(success)){
				throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1007.getErrorNo(),EnumBusinessCode.BUSINESS_1007.getErrorInfo());
			}
        } catch (ServiceCodeException e) {
            throw e;
        } catch (BusinessBaseException e) {
            throw new ServiceCodeException(Integer.valueOf(e.getErrorCode()),e.getMessage());
        } catch (Exception e) {
            throw new ServiceException(e);
        }
	}

	@Override
	public void verfiyCheckCode(Long userId, String bizType,String checkCode) throws ServiceCodeException {
		// TODO Auto-generated method stub
		try {
			UserActiveReq req = new UserActiveReq();
			req.setUserId(userId);
			req.setSendType("sms");
			req.setType(bizType);
			req.setActiveCode(checkCode);
			boolean success = iActiveService.validateChkCode(req);
			if(!success){
				throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1016.getErrorNo(),EnumBusinessCode.BUSINESS_1016.getErrorInfo());
			}
        } catch (ServiceCodeException e) {
            throw e;
        } catch (BusinessBaseException e) {
            throw new ServiceCodeException(Integer.valueOf(e.getErrorCode()),e.getMessage());
        } catch (Exception e) {
            throw new ServiceException(e);
        }
	}
	

	@Override
	public boolean checkUniqueOfPhone(Long userId, String phone) throws ServiceCodeException {
		return remoteUcService.checkAttrValueUnique("cellPhone", phone, userId, Integer.valueOf(exchangeId));
	}

	@Override
	public boolean checkUniqueOfAccount(Long userId, String account) throws ServiceCodeException {
		return remoteUcService.checkAttrValueUnique("account", account, userId, Integer.valueOf(exchangeId));
	}

	private UserAccountDTO convertFrom(Map<String,String> map){
		if (map==null){
			return null;
		}
		UserAccountDTO userAccountDTO = new UserAccountDTO();
		userAccountDTO.setId(Long.valueOf(map.get("userId")));
		userAccountDTO.setAccount(map.get("account"));
		userAccountDTO.setName(map.get("name"));
		userAccountDTO.setFullName(map.get("partFullName"));
		userAccountDTO.setNickName(map.get("partShortName"));
		userAccountDTO.setPhone(map.get("cellPhone"));
		userAccountDTO.setFundAccount(map.get("fundAccount"));
		userAccountDTO.setPartCode(map.get("partCode"));
		userAccountDTO.setTaAccount(map.get("taAccount"));
		userAccountDTO.setStatus(map.get("status"));
		userAccountDTO.setStatusDesc(map.get("statusDesc"));
		userAccountDTO.setCertificateType(map.get("certType"));
		userAccountDTO.setCertificateNum(map.get("certNo"));
		userAccountDTO.setGender(map.get("gender"));
		userAccountDTO.setEmail(map.get("perEmail"));
		String ageString = map.get("age");
		userAccountDTO.setAge(StringUtils.isNotEmpty(ageString)?Integer.valueOf(ageString):null);
		userAccountDTO.setRemak(map.get("commonRemark"));
		userAccountDTO.setBankCard(map.get("bankAccount"));
		userAccountDTO.setHeadImgUrl(map.get("profilePicture"));//个人头像URL
		if (map.containsKey("contactor") && !StringUtil.isEmpty(map.get("contactor"))) {
			userAccountDTO.setContact(map.get("contactor"));
		} else {
			userAccountDTO.setContact(map.get("name"));
		}
		userAccountDTO.setParentAgentUser(map.get("parentAgentUser"));
		userAccountDTO.setParentMidUser(map.get("parentMidUser"));
		userAccountDTO.setFr(map.get("fr"));
		userAccountDTO.setMchtLevel(map.get("mchtLevel"));
		userAccountDTO.setCertFrontImgUrl(map.get("imgAttach1"));
		userAccountDTO.setCertReverseImgUrl(map.get("imgAttach9"));
		userAccountDTO.setAuditRemark(map.get("auditRemark"));
		userAccountDTO.setIntegral(map.get("integral"));
		userAccountDTO.setPartCategories1(map.get("partCategories1"));
		return userAccountDTO;
	}

	@Override
	public UserLoginResult getUserListByNickName(UserLoginInfo request) {
		UserLoginResult result = new UserLoginResult();
		try {
			UserRequest req = new UserRequest();
			Map<String, Object> queryMap=new HashMap<String, Object>();
			if(request.getNickName()!=null){
				//req.setAccount(request.getUserAccount());
				queryMap.put("partShortName", request.getNickName());
			}			
			req.setQueryMap(queryMap);
			req.setParentId(-1L);
			req.setFormCode("MCHT_USER_FORM");
			List<Map<String, String>> list = remoteUcService.getUsersListfromDb(req);
			List<UserAccountDTO> userAccountDTOs = new ArrayList<UserAccountDTO>();
			if (list != null && list.size() > 0) {
				for(Map<String, String> map:list){
					userAccountDTOs.add(convertFrom(map));
				}				
				result.setUserAccountDTOs(userAccountDTOs);
			} else {
				logger.error("交易商" + request.getUserAccount() + "信息异常");
			}
		} catch (Exception e) {
			logger.error("", e);
		}
		return result;
	}

    @Override
    public String updateHeadImgOfUser(Long userId, String headImgBase64) throws ServiceCodeException {
        //先上传头像图片
        try {
            UploadFileResult uploadResult = remoteBidService.uploadFileByte(Base64Util.decodeBase64(headImgBase64), EnumFileType.IMAGE.getCode());
            if(EnumYesOrNo.YES.getCode().equals(uploadResult.getIsSuccess())){
              //更新会员头像存储信息
              String headImgUrl = uploadResult.getAccessUrl();
              UserAccountDTO updateDto = new UserAccountDTO();
              updateDto.setId(userId);
              updateDto.setHeadImgUrl(headImgUrl);
              modifyUser(updateDto);
              return headImgUrl;
            }else{
                throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1017.getErrorNo(),EnumBusinessCode.BUSINESS_1017.getErrorInfo());
            }
        } catch (ServiceCodeException e) {
            throw e;
        } catch (BusinessBaseException e) {
            throw new ServiceCodeException(Integer.valueOf(e.getErrorCode()),e.getMessage());
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

	@Override
	public ThirdLoginDTO validateBindStatus(String unionid,String type) throws ServiceCodeException {
		ThirdLoginDTO thirdLoginDTO = new ThirdLoginDTO();
		UserBindRequest request = new UserBindRequest();
		try{
			request.setIdentifier(unionid);//设置三方用户唯一标识
			request.setIdentityType(type);//设置三方用户类型
			UserBindResponse response=iUcThirdAuthService.validateBindStatus(request);			
			thirdLoginDTO.setBindStatus(response.getStatus());
			if(response.getUserMap()!=null){
				UserAccountDTO userAccountDTO=convertFrom(response.getUserMap());
				userAccountDTO.setPassword(response.getUserMap().get("password"));
				thirdLoginDTO.setUserAccountDTO(userAccountDTO);
			}
		}catch(Exception e){
			logger.error(e);
			throw new ServiceException(e);
		}
		return thirdLoginDTO;
	}

	@Override
	public ThirdLoginDTO bindThirdAccount(Long userId, String unionid,String type) throws ServiceCodeException {
		ThirdLoginDTO thirdLoginDTO = new ThirdLoginDTO();
		UserBindRequest request = new UserBindRequest();
		try{
			request.setUserId(userId);//设置用户信息
			request.setIdentifier(unionid);//设置三方用户唯一标识
			request.setIdentityType(type);//设置三方用户类型
			UserBindResponse response=iUcThirdAuthService.bindThirdAccount(request);		
			thirdLoginDTO.setBindStatus(response.getStatus());
			if(response.getUserMap()!=null){
				UserAccountDTO userAccountDTO=convertFrom(response.getUserMap());
				userAccountDTO.setPassword(response.getUserMap().get("password"));
				thirdLoginDTO.setUserAccountDTO(userAccountDTO);
			}else{
				throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1018.getErrorNo(),EnumBusinessCode.BUSINESS_1018.getErrorInfo());
			}
		}catch(Exception e){
			logger.error(e);
			throw new ServiceException(e);
		}
		return thirdLoginDTO;
	}

	@Override
	public Map<String,String> getAttrValueContent(String mchtLevel) {
		return remoteUcService.getAttrValueContent(mchtLevel,null,null);
	}

    @Override
    public String uploadImg(String imgBase64) {
        //先上传头像图片
        try {
            UploadFileResult uploadResult = remoteBidService.uploadFileByte(Base64Util.decodeBase64(imgBase64), EnumFileType.IMAGE.getCode());
            if(EnumYesOrNo.YES.getCode().equals(uploadResult.getIsSuccess())){
                return uploadResult.getAccessUrl();
            }else{
                throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1018);
            }
        } catch (ServiceCodeException e) {
            throw e;
        } catch (BusinessBaseException e) {
            throw new ServiceCodeException(Integer.valueOf(e.getErrorCode()),e.getMessage());
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

	@Override
	public EmpiricalChangeInfo changeEmpirical(Long userId, Long empiricalValue) {
		EmpiricalChangeReq request = new EmpiricalChangeReq();
		EmpiricalChangeInfo response = new EmpiricalChangeInfo();
		try {
			request.setUserId(userId);
			request.setEmpiricalValue(empiricalValue);
			request.setType(EnumEmpiricalLeveChangeType.UP.getCode());
			EmpiricalChangeResult result= remoteBidService.changeEmpirical(request);
			if (result.getErrorCode() != 1){
				throw new ServiceCodeException(result.errorCode,result.errorMsg);
			}
			response = BeanUtils.transfrom(EmpiricalChangeInfo.class,result);

		}catch (ServiceCodeException e){
			throw e;
		}catch (Exception e){
			throw new ServiceException(e);
		}
		return response;
	}

	@Override
	public void logout(String account, String sessionToken) {
		try {
			UserLoginReq loginReq = new UserLoginReq();
			loginReq.setAccount(account);
			loginReq.setUserToken(sessionToken);
			if (!iMemberService.userLogout(loginReq)) {
				throw new ServiceCodeException(EnumBusinessCode.BUSINESS_3221);
			}
		} catch (ServiceCodeException e) {
			throw e;
		} catch (Exception e) {
			logger.error("统一会员退出接口调用异常",new ServiceException(e));
			throw new ServiceCodeException(EnumCommonCode.COMMON_SERVER_ERROR.getErrorNo(),e.getMessage());
		}
	}

	@Override
	public Boolean checkPassword(Long userId, String passwaord) {
		Boolean result = false;
		try {
			result = remoteUcService.checkPwd(userId,passwaord,EnumPwdType.PAY_PWD.getCode(),null);
		} catch (ServiceCodeException e) {
			throw e;
		} catch (Exception e) {
			logger.error("会员校验支付密码接口调用异常",new ServiceException(e));
			throw new ServiceCodeException(EnumCommonCode.COMMON_SERVER_ERROR.getErrorNo(),e.getMessage());
		}
		return result;
	}

	@Override
	public Map<String, String> validateAccount(String account, String validCode) {
		Map<String,String> resultMap = new HashMap<>();
		//调用会员校验账号是否存在接口，不存在则返回token
		try {

			//临时挡板数据,后续对接会员接口
			resultMap.put("existFlag","Y");//账号是否存在的标识
			resultMap.put("token","hahha1258");//账号不存在时返回的token，提供给三方账户注册并绑定时使用

		} catch (Exception e) {
			logger.error("调用会员校验账号是否存在并返回token的接口异常",new ServiceException(e));
			throw new ServiceCodeException(EnumCommonCode.COMMON_SERVER_ERROR.getErrorNo(),e.getMessage());
		}
		return resultMap;
	}
}
